<template>
    <rk-dialog width="85%"
               height="80%"
               title='评分标准配置'
               :visible="localVisible"
               :destroyOnClose="true"
               @close="localVisible = false"
               :maskClosable="false">
        <template #footer>
            <el-button @click="saveExpertRuleClick" type="primary">保存</el-button>
            <el-button @click="localVisible=false">取消</el-button>
        </template>
        <el-form>
            <el-row class="mb20">
                <el-col :span="12">
                    <el-form-item label="所属区划" label-width="100" :rules="{required:true}">
                        <el-input disabled :model-value="row.adName"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="状态" label-width="100" :rules="{required:true}">
                        <el-select disabled :model-value="row.status">
                            <el-option label="启用" value="1"></el-option>
                            <el-option label="停用" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="mb20">
                <el-col :span="12">
                    <el-form-item label="专家名称" label-width="100" :rules="{required:true}">
                        <el-input disabled :model-value="row.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="身份证号码" label-width="100" :rules="{required:true}">
                        <el-input disabled :model-value="row.idCard"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="mb20">
                <el-col :span="12">
                    <el-form-item label="联系方式" label-width="100" :rules="{required:true}">
                        <el-input disabled :model-value="row.phone"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="电子邮件" label-width="100">
                        <el-input disabled :model-value="row.email"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <rk-grid ref="expertRuleManageRef"
                 title="专家规则维护"
                 :data="currentExpertData"
                 height="75%"
                 box-config
                 :toolbarConfig="{ zoom: false, refresh: false}"
                 :seq-config="false"
                 :pager-config="false"
                 :columns="ruleColumns">
            <template #toolbar_tools>
                <el-button type="primary"
                           @click="localpfAddClick">增加
                </el-button>
                <el-button @click="deleteExpertRuleClick" type="danger">删除</el-button>
            </template>
        </rk-grid>

    </rk-dialog>
    <rk-dialog width="1470"
               height="800"
               title='选择评分标准'
               :visible="localpfVisible"
               :destroyOnClose="true"
               @close="localpfVisible = false"
               :maskClosable="false">
        <template #footer>
            <el-button type="primary"
                       @click="addRulePFClick">确认
            </el-button>
            <el-button @click="localpfVisible=false">取消</el-button>
        </template>
        <rk-grid ref="scoingRef"
                 boxConfig
                 :data="scoinDataList"
                 :columns="ruleColumns"
                 :loading="pfLoading"
                 :pager-config="false"
                 :checkboxConfig="{ reserve: true}">
            <template #toolbar_tools>
                <rk-tree-select enum="EXPERT_SCORE_STATUS"
                                style="margin-right: 12px;"
                                :filterable="false"
                                :showCode="false"
                                :clearable="true"
                                v-model="notAssignQueryParams.scoreType"
                                @change="handlerScoreSearch">
                </rk-tree-select>
            </template>
        </rk-grid>

    </rk-dialog>
</template>

<script setup>
 
import {ElMessage} from "element-plus";
import { useExpertsApi } from '@/api/index'
const  {expertManageAssignRuleList, expertManageNotAssignRuleList, expertManageSaveRule} = useExpertsApi();

const notAssignQueryParams = reactive({
    scoreType: '',
    expertId: '',
    delRuleIds: ''
})

const ruleColumns = ref([
    {
        field: 'entryLev1',
        title: '一级条目',
        width: 250,
        align: 'left',
    },
    {field: 'entryLev2', title: '二级条目', width: 200, align: 'left',},
    {field: 'reviewDesc', title: '评审内容', width: 550, align: 'left',},
    {field: 'reviewStandard', title: '评审标准', width: 220, align: 'left',},
    {
        field: 'scoreType',
        title: '评分选项',
        width: 120,
        align: 'center',
        formatter: ({cellValue}) => {
            return cellValue == 1 ? '分数' : '是/否'
        }
    },
    {
        field: 'scoreRange', title: '分值', width: 200, align: 'center',
        formatter: ({cellValue, row}) => {
            return row.scoreType == 1 ? cellValue : '--'
        }
    },
    {
        field: 'remark', title: '备注', width: 100, align: 'left'
    },
])
const currentExpertData = ref([])
const localVisible = ref(false)
const localpfVisible = ref(false)

const pfLoading = ref(false)

const expertRuleManageRef = ref(null)
const scoingRef = ref(null)
const row = ref({})
const scoinDataList = ref([])
const props = defineProps({
    ok: {
        type: [Promise, Function],
        default: () => {
            return new Promise(resolve => resolve())
        }
    },
    cancel: {
        type: Promise,
        default: () => {
            return new Promise(resolve => resolve())
        }
    }
})

const saveExpertRuleClick = () => {
    let pfbzIds = currentExpertData.value.map(item => {
        return item.pfbzId
    })
    if (!pfbzIds) {
        pfbzIds = [""]
    }
    expertManageSaveRule({expertId: row.value.expertId, ruleIds: pfbzIds.join(",")}).then(resp => {
        if (resp.code === 200) {
            localVisible.value = false
            ElMessage.success("评审规则保存成功！")
            props.ok()
            return
        }
        ElMessage.success("评审规则保存失败！")
    })
}

const deleteExpertRuleClick = () => {
    let seleRows = expertRuleManageRef.value.getCheckboxRecords();
    if (!seleRows || seleRows.length === 0) {
        ElMessage.warning({message: `请至少选择一条数据进行删除！`})
        return
    }
    let deleteIds = seleRows.map(item => {
        return item.pfbzId
    })
    notAssignQueryParams.delRuleIds = deleteIds.join(",")
    currentExpertData.value = currentExpertData.value.filter(val => {
        return !deleteIds.includes(val.pfbzId)
    })
}

const handlerScoreSearch = (data) => {
    pfLoading.value = true
    notAssignQueryParams.scoreType = data || ""
    notAssignQueryParams.expertId = row.value.expertId
    expertManageNotAssignRuleList(notAssignQueryParams).then((resp) => {
        if (resp.code === 200) {
            if (resp.data) {

                if (currentExpertData.value) {
                    let exists = currentExpertData.value.map(item => {
                        return item.pfbzId
                    })
                    scoinDataList.value = resp.data.filter(item => {
                        return !exists.includes(item.pfbzId)
                    })
                } else {
                    scoinDataList.value = resp.data
                }
            }
        }
        pfLoading.value = false
    })
}
const addRulePFClick = () => {
    let seleRows = scoingRef.value.getCheckboxRecords();
    if (!seleRows || seleRows.length === 0) {
        ElMessage.warning({message: `请至少选择一条数据进行添加！`})
        return
    }
    if (notAssignQueryParams.delRuleIds) {
        let delRuleIds = notAssignQueryParams.delRuleIds.split(",")
        seleRows.filter(item => {
            return delRuleIds.includes(item.pfbzId)
        }).forEach(v => {
            let index = delRuleIds.indexOf(v.pfbzId)
            delRuleIds.splice(index, 1)
        })
        notAssignQueryParams.delRuleIds = delRuleIds.join(",")
    }

    currentExpertData.value = sortExpertData(seleRows)
    localpfVisible.value = false
}
const sortExpertData = (rows) => {
    let tempRule = []
    let resultRule = []
    if (currentExpertData.value) {
        tempRule = currentExpertData.value.map(item => {
            return item
        })
    }
    tempRule.push(...rows)
    let temp = {}
    tempRule.forEach(item => {
        if (!temp.hasOwnProperty(item.scoreType)) {
            temp[item.scoreType] = []
        }
        temp[item.scoreType].push(item)
    })
    for (let key in temp) {
        temp[key] = temp[key].sort((v1, v2) => {
            return v1.pfbzOrder - v2.pfbzOrder
        })
    }
    if (temp.hasOwnProperty("2")) {
        resultRule.push(...temp["2"])
    }
    if (temp.hasOwnProperty("1")) {
        resultRule.push(...temp["1"])
    }
    return resultRule
}
const handleOpen = (data) => {
    row.value = data
    notAssignQueryParams.delRuleIds = ""
    expertManageAssignRuleList(row.value.expertId).then(resp => {
        if (resp.code === 200) {
            currentExpertData.value = resp.data || []
        }
    })
    localVisible.value = true
}
const handleClose = () => {
    localVisible.value = false
}

const localpfAddClick = () => {
    localpfVisible.value = true
    handlerScoreSearch()
}

defineExpose({
    handleClose,
    handleOpen
})


</script>

<style scoped lang="scss">

</style>
